/*
 * data: 10150916
 * author: zhliu
 */


#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "qlist.h"
  
int lockless_inqueue(qlist_t *head, qlist_t *tail, qlist_t *new)
{
	qlist_t *q;
	assert(head && tail && new);

	do {
		q = tail->prev;
		new->next = tail;
	} while ( !__sync_bool_compare_and_swap(&q->next, tail, new ));

	tail->prev = new;
	
	return 0;
}

qlist_t *lockless_outqueue(qlist_t *head, qlist_t *tail)
{
	qlist_t *q, *out = NULL;
	assert(head && tail);

	do {
		out = head->next;
		if (q == tail)
			return NULL;

		q = out->next;
	} while ( !__sync_bool_compare_and_swap(&head->next, out, q));

	return out;
}

int lockless_queue_init(qlist_t *head, qlist_t *tail)
{
	if (!head || !tail)
		return -1;

	memset(head, 0x0, sizeof(qlist_t));
	memset(tail, 0x0, sizeof(qlist_t));

	head->next = tail;
	tail->prev = head;

	return 0;
}

#define QTEST 
#ifdef QTEST
qlist_t head, tail;

int main()
{
	if (lockless_queue_init(&head, &tail)) 
		return -1;


	return 0;
}

#endif
